<template>
    <div ref="container" class="app-container">
        <el-row v-if="managedDeptOptions.length>1" class="mb20">
            <el-col :span="24">
                <el-select v-model="currentDept" filterable style="width: 220px">
                    <el-option :value="0" label="全部"></el-option>
                    <el-option v-for="dept in managedDeptOptions" :value="dept.deptId" :label="dept.deptName"></el-option>
                </el-select>
            </el-col>
        </el-row>
        <div class="flex justify-between items-center gap-4">
            <el-card v-for="card in cardOptions" shadow="never" class="flex-1 !rounded-lg">
                <div class="h-18 flex flex-col justify-center items-center gap-2">
                    <el-text>{{ card.label }}</el-text>
                    <span class="font-bold text-4xl cursor-pointer" :class="card.color" @click="goHazardPage(card)">{{ card.value }}</span>
                </div>
            </el-card>
        </div>
        <div class="flex justify-between items-center gap-4 mt20">
            <el-card shadow="never" class="!rounded-lg flex-[3]">
                <div ref="barChart" style="width: 100%; height: 280px"></div>
            </el-card>
            <el-card shadow="never" class="!rounded-lg flex-[2]">
                <div ref="pieChart" style="width: 100%; height: 280px"></div>
            </el-card>
        </div>
        <div v-if="managedDeptOptions.length>1" class="mt20">
            <el-table :data="dashboardData.details" stripe border>
                <el-table-column v-for="col in columns" v-bind="col"/>
            </el-table>
        </div>

        <!-- 预警逻辑组件 -->
        <hazard-alarm v-if="checkPermi(['hazard:alarm'])" />
    </div>
</template>

<script setup name="Index">
import * as echarts from 'echarts'
import {useManagedDept} from "@/hooks/useManagedDept.js";
import {getHazardDashboard, getHazardLevelStatistics, getHazardTypeStatistics} from "@/api/business/hazard.js";
import HazardAlarm from "@/views/components/hazard-alarm.vue";
import {useRouter} from "vue-router";
import {checkPermi} from "@/utils/permission.js";

// common
const router = useRouter()

// data
const {managedDeptOptions} = useManagedDept()
const currentDept = ref(0)
const dashboardData = ref({
    summary: {},
    details: []
})
const columns = [
    {key: 0, label: '部门', prop: 'deptName'},
    {key: 1, label: '隐患总量', prop: 'countAmount'},
    {key: 2, label: '未整改', prop: 'unfinished'},
    {key: 3, label: '已延期', prop: 'delayed'},
    {key: 4, label: '已整改', prop: 'finished'},
    {key: 5, label: '整改率', prop: 'finishedRate'}
]

const container = ref(null)
const barChart = ref(null)
const barOptions = ref(null)
const pieChart = ref(null)
const pieOptions = ref(null)
let observer = null

// computed
const summary = computed(() => {
    if (!currentDept.value) return dashboardData.value.summary
    return dashboardData.value.details.find(d => d.deptId == currentDept.value)
        || {countAmount: 0, unfinished: 0, finished: 0, delayed: 0, finishedRate: '-'}
})
const cardOptions = computed(() => {
    return [
        {label: '隐患总量', value: summary.value.countAmount, color: '!text-main'},
        {label: '未整改', value: summary.value.unfinished, color: '!text-warning', query: {finished: false}},
        {label: '已延期', value: summary.value.delayed, color: '!text-danger', query: {finished: false}},
        {label: '已整改', value: summary.value.finished, color: '!text-success', query: {finished: true}},
        {label: '整改率', value: summary.value.finishedRate, color: '!text-primary'}
    ]
})

// methods
const initBarChart = () => {
    if (!barOptions.value) return
    const chart = echarts.init(barChart.value)
    chart.setOption(barOptions.value)
}

const initPieChart = () => {
    if (!pieOptions.value) return
    const chart = echarts.init(pieChart.value)
    chart.setOption(pieOptions.value)
}

const goHazardPage = (card) => {
    if (!card) return router.push('/docs/hazard/list')
    const payload = card?.query || {}
    if (currentDept.value) payload.deptId = currentDept.value
    const keys = Object.keys(payload)
    const query = keys.length ? {data: encodeURIComponent(JSON.stringify(payload))} : undefined
    router.push({path: '/docs/hazard/list', query: query})
}

const loadDashboardData = async () => {
    const {data} = await getHazardDashboard()
    let countAmount = 0, finished = 0, unfinished = 0, delayed = 0, finishedRate = '-'
    data.forEach(h => {
        countAmount += h.countAmount
        finished += h.finished
        unfinished += h.unfinished
        delayed += h.delayed
        h.finishedRate = '-'
        if (h.countAmount) h.finishedRate = Math.round((h.finished * 100) / h.countAmount) + '%'
    })
    if (countAmount) finishedRate = Math.round((finished * 100) / countAmount) + '%'

    dashboardData.value.details = data
    dashboardData.value.summary = {countAmount, finished, unfinished, delayed, finishedRate}
}

const loadHazardTypeStat = async () => {
    let payload = undefined
    if (currentDept.value) payload = {deptId: currentDept.value}
    const {data} = await getHazardTypeStatistics(payload)
    barOptions.value = {
        title: {
            text: '分类统计',
            left: 'center'
        },
        tooltip: {},
        xAxis: {
            data: data.map(i => i.name)
        },
        grid: {
            bottom: 20
        },
        yAxis: {},
        series: [{
            name: '隐患类型',
            type: 'bar',
            data: data.map(i => i.countNum)
        }]
    }
    initBarChart()
}

const loadHazardLevelStat = async () => {
    let payload = undefined
    if (currentDept.value) payload = {deptId: currentDept.value}
    const {data} = await getHazardLevelStatistics(payload)
    pieOptions.value = {
        color: ['#409EFF', '#E6A23C', '#F56C6C'],
        title: {
            text: '等级统计',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            bottom: '0%',
            left: 'center'
        },
        series: [
            {
                name: '占比',
                type: 'pie',
                radius: '50%',
                data: data.map(i => ({name: i.name, value: i.countNum})),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    }
    initPieChart()
}

// hook
let isFirstMount = false
watch(currentDept, () => {
    loadHazardTypeStat()
    loadHazardLevelStat()
})
onMounted(async () => {
    isFirstMount = true
    await loadDashboardData()
    await loadHazardTypeStat()
    await loadHazardLevelStat()
    isFirstMount = false
})
onActivated(() => {
    // 这里应该是若依的BUG，从菜单初次进入此页时，mount和activate会同时触发
    if (isFirstMount) return
    loadDashboardData()
    loadHazardTypeStat()
    loadHazardLevelStat()
})
onMounted(() => {
    observer = new ResizeObserver((entries) => {
        initBarChart()
        initPieChart()
    })

    if (container.value) {
        observer.observe(container.value)
    }
})
onBeforeUnmount(() => {
    if (observer && container.value) {
        observer.unobserve(container.value)
        observer.disconnect()
    }
})
</script>

<style scoped>

</style>